Toast 元件是一種短暫的提示訊息,目的是讓使用者知道當前做的事情是成功還是失敗,以下來看看如何建立這個元件
Step 1: 建立 Toast 元件
在 src/components 中新增 Toast.vue
<template>
  <teleport to="body">
    <transition name="fade">
      <div v-if="visible" class="toast" :class="type">
        {{ message }}
      </div>
    </transition>
  </teleport>
</template>
<script setup>
import { ref } from 'vue'
const visible = ref(false)
const message = ref('')
const type = ref('success')
function showToast(msg, msgType = 'success', duration = 3000) {
  message.value = msg
  type.value = msgType
  visible.value = true
  setTimeout(() => (visible.value = false), duration)
}
defineExpose({ showToast })
</script>
<style scoped>
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 18px;
  border-radius: 8px;
  color: white;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  opacity: 0.95;
  z-index: 9999;
  transition: all 0.3s ease;
}
.toast.success { background: #4caf50; }
.toast.error { background: #f44336; }
.toast.warning { background: #ff9800; }
.fade-enter-active, .fade-leave-active { transition: opacity 0.3s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
Step2: 在 App.vue 中使用
<script setup>
import Header from './components/Header.vue'
import PostTable from './components/PostTable.vue'
import Toast from './components/Toast.vue'
import { ref } from 'vue'
const toastRef = ref(null)
function showSuccess() {
  toastRef.value.showToast('資料已成功儲存!', 'success')
}
function showError() {
  toastRef.value.showToast('提交失敗,請稍後再試', 'error')
}
</script>
<template>
  <Header />
  <main>
    <button @click="showSuccess">成功</button>
    <button @click="showError">失敗</button>
  </main>
  <!-- Toast 永遠存在於 body -->
  <Toast ref="toastRef" />
</template>
Step3: 整合到表單中
在送出後跳出失敗或成功的提示
emit('submit', newExperience)
toastRef.value.showToast('感謝你的分享!', 'success')
toastRef.value.showToast('提交失敗,請稍後再試', 'error')
defineExpose() 是讓子元素的函式能夠讓父元素使用,而和 defineProps() 與 defineEmits() 差別如下:
| 名稱 | 傳遞方向 | 作用 | 使用場景 | 
|---|---|---|---|
| defineProps() | 父 ➜ 子 | 父元件把資料傳進子元件 | 子元件「接收資料」 | 
| defineEmits() | 子 ➜ 父 | 子元件向父元件發送事件 | 子元件「回報事件」 | 
| defineExpose() | 父 ➜ 子 | 父元件直接存取子元件內部方法或變數 | 父元件「主動控制子元件」 | 
小結
- Toast 提示基本範例
- defineExpose 概念